package com.simpleim.starter.handler;

import com.simpleim.im.common.bean.msg.ProtoMsg;
import com.simpleim.starter.client.ClientSession;
import com.simpleim.starter.protoBuilder.HeartBeatMsgBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class HeartBeatClientHandler extends IdleStateHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatClientHandler.class);

    private static final int READ_IDLE_GAP = 180;

    public HeartBeatClientHandler() {
        super(READ_IDLE_GAP, 0, 0, TimeUnit.SECONDS);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        ClientSession clientSession = ClientSession.getSession(ctx);

        ProtoMsg.Message message = HeartBeatMsgBuilder.buildMsg(clientSession.getUser(), clientSession);
        heartMsg(ctx, message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 读取服务端的响应
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = message.getType();
        // 响应类型是心跳响应
        if (headType == ProtoMsg.HeadType.HEART_BEAT) {
            LOGGER.info("收到服务端的心跳消息：{}", message.getMessageResponse().getInfo());
            return;
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        // 服务端超时检测
    }

    public void heartMsg(ChannelHandlerContext ctx, ProtoMsg.Message message) {
        // 1分钟发送一次
        ctx.executor().schedule(() -> {
            // 发送心跳信息
            if (ctx.channel().isActive()) {
                LOGGER.info(" 发送 HEART_BEAT  消息 to server");
                ctx.writeAndFlush(message);
                heartMsg(ctx, message);
            }
        }, 60, TimeUnit.SECONDS);
    }
}
